<template>
  <div class="boxContent">
    <div class="appBox">
      <div class="searchList">
        <el-form :model="state.params"
                 ref="FormInstance "
                 class="boxFrom">
          <div class="searchBox">
            <template v-for="(item, index) in state.totalInputColumns"
                      :key="index">
              <el-form-item v-if="item.type == 'input'">
                <el-input v-model="state.params[item.key]"
                          clearable
                          :placeholder="item.label"></el-input>
              </el-form-item>
              <el-form-item v-if="item.type == 'select'">
                <el-select v-model="state.params[item.key]"
                           :placeholder="item.label"
                           clearable
                           v-if="item.key == 'cid'">
                  <el-option />
                </el-select>

                <el-cascader v-model="state.params[item.key]"
                             :options="state.propsCity"
                             :props="state.props"
                             :placeholder="item.label"
                             clearable
                             v-if="item.key == 'city'" />
              </el-form-item>
            </template>
          </div>

          <el-form-item class="btns">
            <el-button v-preventReClick
                       type="primary"
                       @click="methods.handleAction('add')"
                       v-permission="1104">创建账号</el-button>
            <el-button v-preventReClick
                       type="primary"
                       plain
                       @click="methods.handleAction('query')">搜索</el-button>
            <el-button v-preventReClick
                       @click="methods.handleAction('reset')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tabaleBox">
        <el-table border
                  v-loading="state.loading"
                  :data="state.tableData"
                  style="width: 100%"
                  :header-cell-style="{ color: '#000' }">

          <el-table-column prop="companyName"
                           label="企业名称"
                           show-overflow-tooltip
                           align="left" />
          <el-table-column prop="account"
                           label="登录手机号"
                           show-overflow-tooltip
                           align="center" />
          <el-table-column prop="userName"
                           label="姓名"
                           show-overflow-tooltip
                           align="center"
                           width="100" />
          <!-- <el-table-column prop="userName"
                           label="用户名称"
                           show-overflow-tooltip
                           align="center"
                           width="100" /> -->
          <el-table-column prop="phone"
                           label="手机号"
                           show-overflow-tooltip
                           align="center"
                           width="140" />
          <el-table-column prop="createdAt"
                           label="创建时间"
                           show-overflow-tooltip
                           align="center"
                           width="180">

          </el-table-column>
          <el-table-column prop="createName"
                           label="创建者"
                           show-overflow-tooltip
                           align="center"
                           width="110">

          </el-table-column>
          <el-table-column prop="roleName"
                           label="角色名称"
                           show-overflow-tooltip
                           align="left">
          </el-table-column>

          <el-table-column prop="status"
                           label="状态"
                           show-overflow-tooltip
                           align="center"
                           width="100">
            <template #default="scope">
              <div v-if="scope.row.status == 0"
                   class="error">禁用</div>
              <div v-if="scope.row.status == 1"
                   class="primary">启用</div>
            </template>
          </el-table-column>
          <el-table-column prop="type"
                           label="平台"
                           show-overflow-tooltip
                           align="center"
                           width="100">
            <template #default="scope">
              <div v-if="scope.row.type == 0"
                   class="">平台</div>
              <div v-if="scope.row.type == 1"
                   class="">企业</div>
            </template>
          </el-table-column>

          <el-table-column prop="updatedAt"
                           label="更新时间"
                           show-overflow-tooltip
                           align="center"
                           width="180">
          </el-table-column>
          <el-table-column prop="updateName"
                           label="更新人"
                           show-overflow-tooltip
                           align="center"
                           width="110">
          </el-table-column>

          <el-table-column prop="btns"
                           label="操作"
                           show-overflow-tooltip
                           align="center"
                           width="170"
                           fixed="right">
            <template #default="scope">
              <div class="flex_c  btnsDatil">
                <!-- <div @click="methods.handleAction('role', scope.row)">授权</div> -->
                <div @click="methods.handleAction('edit', scope.row)"
                     v-permission="1108"
                     class="">编辑</div>
                <div @click="methods.handleAction('usePassword', scope.row)"
                     class="ml12"
                     v-if="scope.row.type == 0"
                     v-permission="1105">修改密码</div>
                <div @click="methods.handleAction('delete', scope.row,1)"
                     v-if="scope.row.status == 0"
                     v-permission="1106"
                     class="ml12 primary">
                  启用
                </div>
                <div @click="methods.handleAction('delete', scope.row,0)"
                     v-permission="1107"
                     v-if="scope.row.status == 1"
                     class="ml12 error">
                  禁用
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination background
                       v-model:current-page="state.params.pageNum"
                       v-model:page-size="state.params.pageSize"
                       :page-sizes="[10, 20, 30, 50]"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="state.totalSize"
                       @size-change="methods.handleSizeChange"
                       @current-change="methods.handleCurrentChange" />
      </div>
      <!-- 授权角色 -->
      <el-dialog v-model="state.dialogShow"
                 center
                 title="授权角色"
                 width="40%"
                 top="15vh">
        <el-table ref="multipleTableRef"
                  :data="state.dialogData.list"
                  style="width: 100%"
                  @selection-change="methods.handleSelectionChange">
          <el-table-column type="selection"
                           width="55" />
          <el-table-column label="企业名称"
                           width="120"
                           prop="name">
          </el-table-column>
          <el-table-column property="companyName"
                           label="角色名称"
                           width="120" />
          <el-table-column property="remark"
                           label="角色备注"
                           show-overflow-tooltip />
        </el-table>
        <div class="mt20 tar">
          <el-button v-preventReClick
                     @click="methods.btnUsbDialog"
                     type="primary">确定授权</el-button>
        </div>
      </el-dialog>
      <!-- 新增账号 -->
      <el-dialog v-model="state.dialogAdd"
                 center
                 title="新建账号"
                 width="40%"
                 top="15vh">
        <el-form ref="ruleFormRef"
                 :model="state.ruleForm"
                 :rules="state.rules"
                 :label-width="$px2rem('90px')"
                 class="demo-ruleForm"
                 :size="formSize"
                 status-icon>
          <el-form-item label="姓名:"
                        prop="userName">
            <el-input v-model="state.ruleForm.userName"
                      placeholder="请输入姓名"
                      @input="state.ruleForm.userName = $input.inputLimit('D10006', state.ruleForm.userName)"
                      clearable />
          </el-form-item>
          <el-form-item label="手机号:"
                        prop="phone">
            <el-input v-model="state.ruleForm.phone"
                      placeholder="请输入绑定手机号作为账号"
                      maxlength="11"
                      @input="state.ruleForm.phone = $input.inputLimit('D10006', state.ruleForm.phone)"
                      clearable />
          </el-form-item>
          <el-form-item label="密码:"
                        prop="password">
            <el-input v-model="state.ruleForm.password"
                      placeholder="请输入密码（6/18位）"
                      type="password"
                      show-password
                      maxlength="18"
                      clearable />
          </el-form-item>
          <el-form-item label="操作密码:"
                        prop="usePassword">
            <el-input v-model="state.ruleForm.usePassword"
                      placeholder="请输入操作密码（6/18位）"
                      type="password"
                      show-password
                      maxlength="18"
                      clearable />
          </el-form-item>

          <el-form-item label="角色:"
                        prop="roleIds">
            <el-select style="width: 100%;"
                       multiple
                       v-model="state.ruleForm.roleIds">
              <el-option v-for="i in state.getRoleIdsData"
                         :key="i"
                         :label="i.name"
                         :value="i.id" />

            </el-select>
          </el-form-item>
          <!-- {{ state.deptIdList }} -->
          <el-form-item label="部门:"
                        prop="deptId">
            <div class="treeBorder">
              <!-- <el-tree :props="state.treeProps"
                         :data="state.deptIdList"
                         show-checkbox
                         ref="dataTree"
                         node-key="id"
                         @check-change="methods.handleCheckChange">
                </el-tree> -->
              <el-scrollbar :height="$px2rem('220px')">
                <el-table :data="state.deptIdList"
                          style="width: 100%; margin-bottom: 20px"
                          row-key="id"
                          border
                          height="200"
                          ref="multipleTableRef1"
                          @selection-change="methods.handleSelectionChange1"
                          :tree-props="{ children: 'childList'}"
                          default-expand-all>
                  <el-table-column type="selection"
                                   align="center"
                                   width="55" />
                  <el-table-column prop="deptName"
                                   label="部门名称" />

                </el-table>
              </el-scrollbar>

            </div>
          </el-form-item>
          <el-form-item label="数据权限:"
                        prop="dataPermission">
            <el-select style="width: 100%;"
                       clearable
                       v-model="state.ruleForm.dataPermission">
              <el-option label="个人"
                         :value="1" />
              <el-option label="部门"
                         :value="2" />
              <el-option label="所有"
                         :value="3" />

            </el-select>
          </el-form-item>

        </el-form>

        <div class="tar pr20 pb20">
          <el-button v-preventReClick
                     @click="state.dialogAdd = false"> 取 消 </el-button>
          <el-button v-preventReClick
                     type="primary"
                     @click="methods.clickSubAdd"> 确 定 </el-button>
        </div>
      </el-dialog>
      <!-- 修改密码 -->
      <el-dialog v-model="state.dialogPass"
                 center
                 title="修改密码"
                 width="30%"
                 top="15vh">
        <div class="demo-ruleForm">
          <el-input v-model="state.tableItemData.account"
                    disabled>
            <template #prepend>登录账号</template>
          </el-input>
          <el-input v-model="state.tableItemData.password"
                    placeholder="请输入原密码"
                    maxlength="18"
                    class="mt20">
            <template #prepend>原密码&emsp;</template>
          </el-input>
          <el-input v-model="state.tableItemData.newPass"
                    class="mt20"
                    type="password"
                    show-password
                    maxlength="18"
                    placeholder="密码长度为6-18位">
            <template #prepend>新密码&emsp;</template>
          </el-input>
          <el-input v-model="state.tableItemData.usePassword"
                    class="mt20"
                    type="password"
                    show-password
                    maxlength="18"
                    placeholder="请输入操作密码">
            <template #prepend>操作密码</template>
          </el-input>
          <div class="mt20 tar">
            <el-button v-preventReClick
                       @click="state.dialogPass = false">
              取 消
            </el-button>
            <el-button v-preventReClick
                       @click="methods.btnSubPass"
                       type="primary">
              提 交
            </el-button>
          </div>

        </div>

      </el-dialog>
      <!-- 编辑账号 -->
      <el-dialog v-model="state.dialogEdit"
                 v-if="state.dialogEdit"
                 center
                 title="编辑账号"
                 width="40%"
                 top="15vh">

        <el-scrollbar :height="state.tableItemData.type != 1 ? '':$px2rem('220px')">
          <div class="demo-ruleForm">
            <div class="">
              <el-form-item label="姓名:"
                            label-width="80px"
                            prop="dataPermission">
                <el-input v-model="state.tableItemData.userName"
                          clearable
                          placeholder="请输入姓名"
                          @input="state.ruleForm.userName = $input.inputLimit('D10006', state.ruleForm.userName)">
                </el-input>
              </el-form-item>
            </div>
            <div class="mt20">
              <el-form-item label="手机号:"
                            label-width="80px"
                            prop="dataPermission">
                <el-input v-model="state.tableItemData.phone"
                          clearable
                          placeholder="请输入手机号"
                          disabled
                          @input="state.ruleForm.phone = $input.inputLimit('D10005', state.ruleForm.phone)">
                </el-input>
              </el-form-item>
            </div>
            <div class="mt20">
              <el-form-item label="角色:"
                            label-width="80px"
                            prop="dataPermission">
                <el-select style="width: 100%;"
                           multiple
                           v-model="state.tableItemData.roleIds">
                  <el-option v-for="i in state.getRoleIdsData"
                             :key="i"
                             :label="i.name"
                             :value="i.id" />

                </el-select>
              </el-form-item>
            </div>
            <div class="mt20"
                 v-if="state.tableItemData.type != 1">
              <el-form-item label="部门:"
                            label-width="80px"
                            prop="dataPermission">
                <div class="treeBorder">
                  <!-- <el-tree :props="state.treeProps"
                           :data="state.deptIdList"
                           show-checkbox
                           ref="dataTree"
                           :default-checked-keys="[state.tableItemData.deptId]"
                           node-key="id"
                           @check-change="methods.handleCheckChange1">
                  </el-tree> -->
                  <el-scrollbar :height="$px2rem('180px')">
                    <el-table :data="state.deptIdList"
                              style="width: 100%; margin-bottom: 20px"
                              row-key="id"
                              border
                              height="200"
                              ref="multipleTableRef2"
                              @selection-change="methods.handleSelectionChange2"
                              :tree-props="{ children: 'childList'}"
                              default-expand-all>
                      <el-table-column type="selection"
                                       align="center"
                                       width="55" />
                      <el-table-column prop="deptName"
                                       label="部门名称" />

                    </el-table>
                  </el-scrollbar>
                </div>
              </el-form-item>
            </div>
            <div class="mt20"
                 v-if="state.tableItemData.type != 1">

              <el-form-item label="数据权限:"
                            label-width="80px"
                            prop="dataPermission">
                <el-select style="width: 100%;"
                           clearable
                           v-model="state.tableItemData.dataPermission">
                  <el-option label="个人"
                             :value="1" />
                  <el-option label="部门"
                             :value="2" />
                  <el-option label="所有"
                             :value="3" />

                </el-select>
              </el-form-item>
            </div>

          </div>
        </el-scrollbar>
        <div class="mt20 tar pr20 pb20">
          <el-button v-preventReClick
                     @click="state.dialogEdit = false">
            取 消
          </el-button>
          <el-button v-preventReClick
                     @click="methods.btnSubEdit"
                     type="primary">
            提 交
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  onMounted,
  reactive,
  getCurrentInstance,
  nextTick,
} from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { styleType } from "element-plus/es/components/table-v2/src/common";
const router = useRouter();
const app = getCurrentInstance()?.proxy;
const initState = () => {
  return {
    loading: false,
    defaultCheckedKeys: [],
    getRoleIdsData: [],
    dialogAdd: false,
    dialogEdit: false,
    dialogPass: false,
    dialogShow: false,
    deptIdList: [],
    treeProps: {
      children: 'childList',
      label: 'deptName'
    },
    tableItemData: {
    },
    dialogData: {
      roleIds: [],
      data: {},
      rolesList: [],
    },
    totalSize: 0,
    tableData: [],
    params: {
      pageNum: 1,
      pageSize: 10,
      userName: "",
      phone: "",
      account: "",
      dataPermission: "",
      deptId: '',
    },
    ruleForm: {
      account: '',
      password: '',
      phone: '',
      userName: '',
      roleIds: [],
      type: 0,
    },
    rules: {
      account: [{
        required: true,
        message: '请输入账号',
        trigger: 'blur',
      }],
      deptId: [{
        required: true,
        message: '请选择部门',
        trigger: 'change',
      }],
      dataPermission: [{
        required: true,
        message: '请选择数据权限',
        trigger: 'change',
      }],
      password: [{
        required: true,
        message: '请输入密码',
        trigger: 'change',
      }],
      usePassword: [{
        required: true,
        message: '请输入操作密码',
        trigger: 'blur',
      }],
      phone: [{
        required: true,
        message: '请输入绑定手机号作为账号',
        trigger: 'change',
      }, { min: 11, max: 11, message: '长度为11位', trigger: 'blur' },],
      userName: [{
        required: true,
        message: '请输入姓名',
        trigger: 'blur',
      }],
      roleIds: [{
        required: true,
        message: '请选择角色',
        trigger: 'change',
      }],

    },
    totalInputColumns: [
      { key: "userName", label: "姓名", type: "input" },
      { key: "phone", label: "手机号", type: "input" },
      { key: "account", label: "登录手机号", type: "input" },
      { key: "companyName", label: "企业名称", type: "input" },
    ],
  };
};
const state = reactive(initState());
onMounted(() => {
  methods.getDataList();
  methods.getDeptIdList()
});
const methods = {

  // 修改密码
  btnSubPass () {
    if (!state.tableItemData.password) {
      ElMessage({ type: 'error', message: '请输入原密码' })
      return
    }
    if (!state.tableItemData.newPass) {
      ElMessage({ type: 'error', message: '请输入新密码' })
      return
    }
    if (!state.tableItemData.usePassword) {
      ElMessage({ type: 'error', message: '请输入操作密码' })
      return
    }

    let data = {
      id: state.tableItemData.id,
      newPassword: state.tableItemData.newPass,
      oldPassword: state.tableItemData.password,
      usePassword: state.tableItemData.usePassword,
    }
    app.$http.post('/sysuser/account/edit/password', data).then(res => {
      if (res.code == 200) {
        ElMessage({ type: 'success', message: '修改成功' })
        state.tableItemData = {}
        state.dialogPass = false
      }
    })
  },
  // 表格多选
  handleSelectionChange (e) {
    console.log(e, "表格多选");
    state.dialogData.roleIds = e.map((res) => res.id);
  },
  // 表格多选
  handleSelectionChange1 (val) {
    state.ruleForm.deptId = val[0].id
    if (val.length > 1) {
      app.$refs.multipleTableRef1.clearSelection();
      app.$refs.multipleTableRef1.toggleRowSelection(val.pop());
    }
  },
  handleSelectionChange2 (val) {
    if (val[0]) {
      state.tableItemData.deptId = val[0].id
    }
    if (val.length > 1) {
      app.$refs.multipleTableRef2.clearSelection();
      app.$refs.multipleTableRef2.toggleRowSelection(val.pop());
    }
  },

  // 获取部门
  getDeptIdList () {
    app.$post('sysDept/getList', {}).then(res => {
      if (res.code == 200) {
        state.deptIdList = res.data
      }
    })
  },
  // 编辑角色
  btnSubEdit () {
    app.$http.post('/sysuser/account/edit/account', {
      uid: state.tableItemData.id,
      userName: state.tableItemData.userName,
      roleIds: state.tableItemData.roleIds,
      phone: state.tableItemData.phone,
      deptId: state.tableItemData.deptId,
      dataPermission: state.tableItemData.dataPermission,

    }).then(res => {
      if (res.code == 200) {
        ElMessage({ type: 'success', message: '修改成功' })
        state.tableItemData = {}
        methods.getDataList()
        state.dialogEdit = false
      } else {
        ElMessage({ type: 'error', message: res.message })
      }
    })
  },
  // 获取详情
  listDetails () {
    app.$http.get('/sysuser/account/getUserInfo?uid=' + state.tableItemData.id).then(res => {
      if (res.data.roles) {
        state.tableItemData.type = res.data.type
        state.tableItemData.deptId = res.data.deptId
        state.tableItemData.dataPermission = res.data.dataPermission
        state.tableItemData.roleIds = res.data.roles.map(a => a.id)
        methods.tableSelect(state.deptIdList)

      }
    })
  },
  // 递归 回显选中的表格
  tableSelect (childList) {
    childList.forEach(res => {
      if (res.id == state.tableItemData.deptId) {
        nextTick(() => {
          return app.$refs.multipleTableRef2.toggleRowSelection(res)
        })
      } else {
        methods.tableSelect(res.childList)
      }
    })
    // 
  },
  // 新增账号
  clickSubAdd () {
    app.$refs.ruleFormRef.validate((valid) => {
      if (valid) {
        const loading = ElLoading.service({
          text: "加载中",
        });
        app.$http.post('/sysuser/account/register', state.ruleForm).then(res => {
          if (res.code == 200) {
            state.ruleForm = initState().ruleForm
            app.$refs.multipleTableRef1.clearSelection();
            state.dialogAdd = false
            methods.getDataList()
          }
          loading.close()
        }).catch(() => {
          loading.close()
        })
      } else {
        return
      }
    })
  },
  // 操作按钮
  handleAction (type, data, status) {
    switch (type) {
      case "add": //新增账号
        methods.getRoleIds()
        state.dialogAdd = true
        break;
      case "role": //授权
        methods.roleHasMenuList(data);
        state.dialogData.data = data;
        state.dialogShow = true;
        break;
      case "query": //查询
        methods.getDataList();
        break;
      case "reset": // 重置
        state.params = initState().params;
        break;
      case "edit": // 编辑
        Object.assign(state.tableItemData, data)
        methods.getRoleIds()
        methods.listDetails()
        state.dialogEdit = true
        break;
      case "usePassword": // 修改密码
        Object.assign(state.tableItemData, data)
        state.tableItemData.newPass = ''
        state.dialogPass = true
        break;
      case "delete": // 删除
        app.$http.get("/sysuser/account/delete/user?uid=" + data.id + '&status=' + status).then((res) => {
          methods.getDataList();
          ElMessage({
            type: "success",
            message: "操作成功",
          });
        });


        break;
    }
  },
  // 角色列表
  getRoleIds () {
    app.$get('/sys/role/getRoleListCreateSysUser',
      {
        type: state.tableItemData.type || 0,
        id: state.tableItemData.id || JSON.parse(localStorage.getItem('userInfor')).uid
      }
    ).then(res => {
      if (res.data) {
        state.getRoleIdsData = res.data
      }
    })
  },
  // 获取授权数据
  btnUseInfor (data) {
    app.$http.get("/sysuser/account/getUserInfo?uid=" + data.id).then((res) => {
      if (res.data.roles) {
        state.dialogData.rolesList = res.data.roles;
        res.data.roles.forEach((i) => {
          state.dialogData.list.forEach((k) => {
            if (i.id == k.id) {
              nextTick(() => {
                app.$refs.multipleTableRef.toggleRowSelection(k);
              });
            }
          });
        });
      }
    });
  },
  // 确定授权
  btnUsbDialog () {
    app.$http
      .post("/sysuser/account/edit/account", {
        roleIds: state.dialogData.roleIds,
        uid: state.dialogData.data.id,
        userName: state.dialogData.data.userName,
      })
      .then((res) => {
        ElMessage({ type: "success", message: "授权成功" });
        methods.getDataList()
        state.dialogShow = false
      });
  },
  // 获取用户可被授权的角色
  roleHasMenuList (data) {
    app.$http.get("/sys/role/has/menu/byuid?uid=" + data.id).then((res) => {
      state.dialogData.list = res.data;
      methods.btnUseInfor(data);
    });
  },
  // 主数据
  getDataList () {
    state.loading = true
    app.$http
      .post("/sysuser/account/pageInfo", state.params)
      .then((res) => {
        state.tableData = res.data.list;
        state.totalSize = res.data.total;
        state.loading = false
      }).catch(() => {
        state.loading = false
      })
  },
  //分页变化
  handleSizeChange () {
    state.params.pageNum = 1;
    methods.getDataList();
  },
  //表格翻页
  handleCurrentChange () {
    methods.getDataList();
  },
};
</script>

<style lang="scss" scoped>
.treeBorder {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  ::v-deep(.el-table__header-wrapper) {
    .el-checkbox {
      display: none !important;
    }
  }
}
.appBox {
  background: #fff;
  border-radius: 5px;
  padding: 20px;
  height: calc(100% - 20px);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .demo-ruleForm {
    padding: 20px 40px 20px 30px;
  }
  .tabaleBox {
    overflow: hidden;
    flex: 1;
  }
  .btnsDatil {
    color: #0079fe;
    cursor: pointer;
  }
  .pagination {
    margin-top: 20px;
    height: 50px;
    display: flex;
    justify-content: flex-end;
  }
  ::v-deep(.el-dialog__body) {
    max-height: 680px;
  }
  .imgs {
    flex-wrap: wrap;
    .forbox {
      // width: 150px;
      height: 150px;
      margin: 10px 0 0 10px;
    }
    .imgBox {
      height: 100%;
      width: auto;
    }
    .videoBox {
      width: auto;
      height: 100%;
    }
  }

  // .imgs .forbox:nth-child(4n + 1) {
  //   margin-left: 0;
  // }
}
</style>
